package com.centling.smartSealForPhone.db;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.text.TextUtils;

import com.centling.smartSealForPhone.application.SmartSeal;
import com.example.localalbum.common.LocalImageHelper;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * @author fionera
 */
public class DbControl {
    private SQLiteDatabase db;
    private ContentValues values;
    private static DbControl dbControl;

    private DbControl(Context context) {
        DbHelper helper = new DbHelper(context, DbConstance.DB_NAME);
        this.db = helper.getWritableDatabase();
    }

    public static DbControl getInstance() {
        if (dbControl == null) {
            synchronized (DbControl.class) {
                if (dbControl == null) {
                    dbControl = new DbControl(SmartSeal.getInstance());
                }
            }
        }
        return dbControl;
    }

    /**
     * 查找表中所有数据
     */
    public List<ImageBean> selectAll() {
        List<ImageBean> users = new ArrayList<>();
        Cursor cursor = db.query(DbConstance.TABLE_NAME, new String[]{DbConstance.ID, DbConstance.TYPE, DbConstance.TASK_ID, DbConstance.USER_ID, DbConstance.PATHS, DbConstance.BACK_ID, DbConstance.COMPANY_CODE, DbConstance.DATE}, null, null, null, null, null, null);
        while (cursor.moveToNext()) {
            ImageBean img = new ImageBean();
            img.setId(cursor.getInt(cursor.getColumnIndex(DbConstance.ID)));
            img.setTaskId(cursor.getString(cursor.getColumnIndex(DbConstance.TASK_ID)));
            img.setType(cursor.getString(cursor.getColumnIndex(DbConstance.TYPE)));
            img.setUserId(cursor.getString(cursor.getColumnIndex(DbConstance.USER_ID)));
            img.setPaths(cursor.getString(cursor.getColumnIndex(DbConstance.PATHS)));
            img.setBackId(cursor.getString(cursor.getColumnIndex(DbConstance.BACK_ID)));
            img.setCompanyCode(cursor.getString(cursor.getColumnIndex(DbConstance.COMPANY_CODE)));
            img.setDate(cursor.getString(cursor.getColumnIndex(DbConstance.DATE)));
            users.add(img);
        }
        cursor.close();
        return users;
    }

    /**
     * 查询报警表中的所有数据
     */
    List<WarnBean> selectWarningData() {
        List<WarnBean> warnList = new ArrayList<>();
        Cursor cursor = db.query(DbConstance.TABLE_WARN, new String[]{DbConstance.PROCESSFLAG, DbConstance.PROCESSID, DbConstance.ALARMMSG,
                DbConstance.LATITUDE, DbConstance.LONGTITUDE, DbConstance.ALARMLOACATION, DbConstance.COMPANY_CODE}, null, null, null, null, null, null);
        while(cursor.moveToNext()){
            WarnBean waringBean = new WarnBean();
            waringBean.setProcessFlag(cursor.getString(cursor.getColumnIndex(DbConstance.PROCESSFLAG)));
            waringBean.setProcessId(cursor.getString(cursor.getColumnIndex(DbConstance.PROCESSID)));
            waringBean.setAlarmMsg(cursor.getString(cursor.getColumnIndex(DbConstance.ALARMMSG)));
            waringBean.setLatitude(cursor.getString(cursor.getColumnIndex(DbConstance.LATITUDE)));
            waringBean.setLongitude(cursor.getString(cursor.getColumnIndex(DbConstance.LONGTITUDE)));
            waringBean.setAlarmLocation(cursor.getString(cursor.getColumnIndex(DbConstance.ALARMLOACATION)));
            waringBean.setCompanyCode(cursor.getString(cursor.getColumnIndex(DbConstance.COMPANY_CODE)));
            warnList.add(waringBean);
        }
        cursor.close();
        return warnList;
    }

    public List<String> selectFiveUsers() {
        List<String> userList=new ArrayList<>();
        Cursor cursor = db.rawQuery("select * from " + DbConstance.TABLE_USER + " order by _id desc limit 5", null);
        while(cursor.moveToNext()) {
            String applyUser=cursor.getString(cursor.getColumnIndex(DbConstance.USERNAME)) + " " +
                    cursor.getString(cursor.getColumnIndex(DbConstance.TELEPHONE));
            userList.add(applyUser);
        }
        cursor.close();
        return userList;
    }

    public void updateId(String tele) {
        Cursor cursor = db.rawQuery("select max(_id) from " + DbConstance.TABLE_USER, null);
        int maxId = 0;
        while (cursor.moveToNext()) {
            maxId = cursor.getInt(0);
        }
        db.execSQL("update " + DbConstance.TABLE_USER + " set _id=? where telephone=?",
                new Object[]{maxId + 1 + "", tele});
        cursor.close();
    }

    public boolean hasUserByTelephone(String tele) {
        Cursor cursor = db.rawQuery(
                "select * from " + DbConstance.TABLE_USER + " where telephone=?",
                new String[]{tele});
        if (cursor.moveToNext()) {
            cursor.close();
            return true;
        } else {
            cursor.close();
            return false;
        }
    }

    /**
     * 用户表插入数据
     */
    public void insertUserData(String username, String telephone) {
        values = new ContentValues();
        values.put(DbConstance.USERNAME, username);
        values.put(DbConstance.TELEPHONE, telephone);
        db.insert(DbConstance.TABLE_USER, null, values);
    }

    /**
     * 插入一行数据
     */
    public void insertData(String type, String taskId, String userId, String backId,
                           String path) {
        values = new ContentValues();
        values.put(DbConstance.TYPE, type);
        values.put(DbConstance.TASK_ID, taskId);
        values.put(DbConstance.USER_ID, userId);
        values.put(DbConstance.BACK_ID, backId);
        values.put(DbConstance.COMPANY_CODE, SmartSeal.getInstance().getIp());
        values.put(DbConstance.DATE, String.valueOf(System.currentTimeMillis()));
        values.put(DbConstance.PATHS, path);
        db.insert(DbConstance.TABLE_NAME, null, values);
    }

    /**
     * 插入多行数据
     */
    public void insertData(String type, String taskId, String userId, String backId,
                           List<LocalImageHelper.LocalFile> files) {
        for (int i = 0; i < files.size(); i++) {
            if (!TextUtils.isEmpty(files.get(i).getApplyDocPicId())) {
                continue;
            }
            values = new ContentValues();
            values.put(DbConstance.TYPE, type);
            values.put(DbConstance.TASK_ID, taskId);
            values.put(DbConstance.USER_ID, userId);
            // fuck regen uuid here
            String backIdTemp = backId;
            if (TextUtils.equals("0", backIdTemp)) {
                backIdTemp = UUID.randomUUID().toString();
            }
            values.put(DbConstance.BACK_ID, backIdTemp);
            values.put(DbConstance.COMPANY_CODE, SmartSeal.getInstance().getIp());
            values.put(DbConstance.DATE, String.valueOf(System.currentTimeMillis()));
            values.put(DbConstance.PATHS, files.get(i).getPath());
            db.insert(DbConstance.TABLE_NAME, null, values);
        }
    }

    /**
     * @param type   类型，0申请用印人头像，1申请文件照片，2盖章时文件照片，3补拍文件
     * @param taskId type为3时，使用复审id，其他为用印申请id
     * @param userId 用户id
     * @param ids    type为2时，盖章授权id，type为3时，失败照片id
     * @param files  文件
     */
    public void insertData(String type, String taskId, String userId, List<String> ids,
                           List<LocalImageHelper.LocalFile> files) {
        for (int i = 0; i < files.size(); i++) {
            values = new ContentValues();
            values.put(DbConstance.TYPE, type);
            values.put(DbConstance.TASK_ID, taskId);
            values.put(DbConstance.USER_ID, userId);
            values.put(DbConstance.BACK_ID, ids.get(i));
            values.put(DbConstance.COMPANY_CODE, SmartSeal.getInstance().getIp());
            values.put(DbConstance.DATE, String.valueOf(System.currentTimeMillis()));
            values.put(DbConstance.PATHS, files.get(i).getPath());
            db.insert(DbConstance.TABLE_NAME, null, values);
        }
    }

    /**
     * 报警表插入数据
     */
    public void insertWarningData(String processFlag, String processId, String alarmMsg,
                                  String latitude, String longitude, String alarmLocation) {
        values = new ContentValues();
        values.put(DbConstance.PROCESSFLAG, processFlag);
        values.put(DbConstance.PROCESSID, processId);
        values.put(DbConstance.ALARMMSG, alarmMsg);
        values.put(DbConstance.LATITUDE, latitude);
        values.put(DbConstance.LONGTITUDE, longitude);
        values.put(DbConstance.ALARMLOACATION, alarmLocation);
        values.put(DbConstance.COMPANY_CODE, SmartSeal.getInstance().getIp());
        db.insert(DbConstance.TABLE_WARN, null, values);
    }

    /**
     * 根据_id删除一行数据,因为id是唯一的
     */
    public void deleteData(int id) {
        String mId = id + "";
        db.delete(DbConstance.TABLE_NAME, "_id=?", new String[]{mId});
    }

    void deleteWarnData(String id) {
        String mId = id + "";
        db.delete(DbConstance.TABLE_WARN, "processId=?", new String[]{mId});
    }

    public void close() {
        db.close();
    }
}
